import pymysql
from pyecharts.charts import Pie
from pyecharts import options

# 连接数据库
db = pymysql.connect(
    host="localhost",
    user="root",
    password="1201",
    database="crawlerdemo",
    charset="utf8"
)

# 创建游标对象
cursor = db.cursor()

# SQL查询语句，获取总岗位量
sql_total = "SELECT COUNT(*) FROM job"

# SQL查询语句，获取各城市岗位量
sql_cities = "SELECT job_place, COUNT(job_id) FROM job GROUP BY job_place ORDER BY COUNT(job_id) DESC LIMIT 5"

try:
    # 执行查询总岗位量的SQL语句
    cursor.execute(sql_total)
    total_jobs = cursor.fetchone()[0]

    # 执行查询各城市岗位量的SQL语句
    cursor.execute(sql_cities)
    res = cursor.fetchall()

    # 计算各城市岗位量占比
    data = [(city, count / total_jobs) for city, count in res]

    pie = Pie()
    pie.add("单位/个", data, radius=["40%", "75%"])
    # 创建饼图对象
    pie.set_global_opts(title_opts=options.TitleOpts(title="各城市岗位量占比"))
    pie.render("piera.html")
except Exception as e:
    print("查询出错啦:", e)
finally:
    cursor.close()
    db.close()
